#include "threadPool.h"
int exitPipe[2];//0读1写
void handler(int num)
{   
    printf("信号被触发了\n");
    write(exitPipe[1],"1",1);
}
int main(int argc,char* argv[])//master进程
{
    pipe(exitPipe);
    if(fork())//父进程
    {
        close(exitPipe[0]);
        signal(SIGUSR1,handler);
        wait(NULL);
        printf("son thread is exit\n");
        exit(0);
    }
    //子进程初始化
    close(exitPipe[1]);
    threadPool_t threadPool;
    int workerNum=atoi(argv[3]);
    threadPoolInit(&threadPool,workerNum);
    makeworker(&threadPool);
    int sockfd=initTcp(argv[1],argv[2]);
    int epfd=epoll_create(1);
    epollAdd(epfd,sockfd);
    epollAdd(epfd,exitPipe[0]);
    struct epoll_event readyset;
    printf("master初始化完成\n");
    while(1)
    {
        epoll_wait(epfd,&readyset,1,-1);
        if(readyset.data.fd==sockfd)//有新连接到来
        {
            int netfd=accept(sockfd,NULL,NULL);
            printf("新连接到来 %d\n",netfd);
            
            pthread_mutex_lock(&threadPool.mutex);
            printf("i am master i get netfd %d\n",netfd);
            enQueue(&threadPool.taskQueue,netfd);
            pthread_cond_broadcast(&threadPool.cond);
            pthread_mutex_unlock(&threadPool.mutex);
        }
        else if(readyset.data.fd==exitPipe[0])
        {
            printf("信号被触发，执行退出工人逻辑\n");
            pthread_mutex_lock(&threadPool.mutex);
            threadPool.exitFlag=1;
            pthread_cond_broadcast(&threadPool.cond);
            pthread_mutex_unlock(&threadPool.mutex);
            for(int i=0;i<workerNum;i++)
            {
                pthread_join(threadPool.tidArr.arr[i],NULL);
            }
            exit(0);
        }
    }

    return 0;
}

